package com.zzqstart.vod.controller;


import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.netflix.client.ClientException;
import com.zzqstart.commonutils.R;
import com.zzqstart.vod.service.VodService;
import com.zzqstart.vod.utils.ConstantPropertiesUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * ClassName: VodController
 * Package: com.atguigu.vod.controller
 * Description:
 *
 * @Author zzqstart
 * @Create 2023-02-27 1:56
 * @Version 1.0
 */
@RestController
@RequestMapping("/vodservice")
public class VodController {

    @Autowired
    private VodService vodService;

    @PostMapping("/saveVideo")
    public R saveVideo(MultipartFile file) {
        String videoId = vodService.saveVideo(file);
        return R.ok().data("videoId", videoId);
    }

    @DeleteMapping("/deleteBatchVideoById")
    public R deleteVideoById(@RequestParam("videoIdList") List<String> videoIdList) throws ClientException {
        vodService.deleteVideoById(videoIdList);
        return R.ok();
    }

    @DeleteMapping("/deleteAllVideoByCourseId")
    public R deleteAllVideoByCourseId(@RequestParam("courseId") String courseId) throws ClientException {
        vodService.deleteAllVideoByCourseId(courseId);
        return R.ok();
    }

    @ApiOperation(value = "根据视频id获取视频播放凭证")
    @GetMapping("/getvideoplayauth/{videoId}")
    public R getvideoplayauth(@PathVariable String videoId) {
        if (StringUtils.isEmpty(videoId) || videoId.equals("null")) {
            return R.ok();
        }

        String regionId = "cn-shanghai";  // 点播服务接入地域
        DefaultProfile profile = DefaultProfile.getProfile(regionId, ConstantPropertiesUtils.KEY_ID, ConstantPropertiesUtils.KEY_SECRET);
        DefaultAcsClient client = new DefaultAcsClient(profile);
        GetVideoPlayAuthResponse response = new GetVideoPlayAuthResponse();
        try {
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
            request.setVideoId(videoId.trim());
            response = client.getAcsResponse(request);
            //播放凭证
            String playAuth = response.getPlayAuth();
            //VideoMeta信息
            return R.ok().data("playAuth", playAuth);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.error().message("视频资源不存在");
    }
}
